#!/usr/bin/env python
# -*- coding: utf-8 -*-
#code:utf-8
#
# Copyright(C) 2011 SupDo.com
# Licensed under the GUN License, Version 3.0 (the "License");
# 
# File:        userView.py
# Author:      KuKei
# Create Date: 2011-04-18
# Description: 用户管理视图
# Modify Date: 2011-04-18

from sd.cms.views import BaseView
from sd.cms.lib.decorator import powerLevel
from sd.cms.lib import Params, Pager
from sd.cms.forms.userForm import UserForm, LoginForm
from sd.cms.models.userModel import User
import datetime, hashlib

class UserView(BaseView):
    def add(self, **args):
        now = datetime.datetime.now()
        self.viewData['current_date'] = now
        userForm = UserForm()
        oldUser = None
        if self.request.POST:
            userForm = UserForm(self)
            if userForm.is_valid():
                userData = userForm.cleaned_data
                userData['password'] = hashlib.sha1(userData['password']).hexdigest()
                userData['power'] = self.params.USER
                userData['crtip'] = self.request.META['REMOTE_ADDR']
                userData['crtdate'] = datetime.datetime.now()
                userModel = User().initData(userData)
                userModel.save()
                return self.redirect('list!User.html')
        self.viewData['userForm'] = userForm
        return self.render('/addUser.html')
    
    @powerLevel(Params.USER)
    def edit(self, **args):
        now = datetime.datetime.now()
        self.viewData['current_date'] = now
        userForm = UserForm()
        oldUser = None
        if self.request.POST:
            userForm = UserForm(self)
            if userForm.is_valid():
                userData = userForm.cleaned_data
                userData['password'] = hashlib.sha1(userData['password']).hexdigest()
                #如果存在_id,就做更新，不存在就添加
                userId = int(self.request.POST['_id'])
                if userId>-1:
                    oldUser = User.objects.filter(id=userId)[0]
                    userData['power'] = oldUser.power
                    userData['crtip'] = oldUser.crtip
                    userData['crtdate'] = oldUser.crtdate
                    userModel = User().initData(userData)
                    userModel.id = oldUser.id
                    userModel.save()
                else:
                    pass
                return self.redirect('list!User.html')
        self.viewData['userForm'] = userForm
        return self.render('/addUser.html')
    
    @powerLevel(Params.ADMINISTRATOR)
    def delete(self, **args):
        User.objects.filter(id=int(args['id'])).delete()
        return self.redirect('listUser.html')
    
    #用户登录验证函数
    def login(self, **args):
        is_valid = False;
        loginForm = LoginForm()
        if self.request.POST:
            loginForm = LoginForm(self)
            if loginForm.is_valid():
                user = User.objects.filter(username=loginForm.data['username'])
                if len(user)>0:
                    if hashlib.sha1(loginForm.data['password']).hexdigest() == user[0].password:
                        self.power = {'isLogin':True,'user':user[0]}
                        self.request.session[self.params.POWER] = self.power
                        self.viewData['site'][self.params.POWER] = self.power
                        is_valid = True
                    else:
                        loginForm.errors['password'] = loginForm.error_class(['密码有误！'])
                else:
                    loginForm.errors['username'] = loginForm.error_class(['无此用户！'])
        if is_valid:
            return self.redirect(self.request.GET['_toUrl'] if self.request.GET and self.request.GET.has_key('_toUrl') else '/')
        else:
            if self.params.POWER in self.request.session:
                self.request.session.pop(self.params.POWER)
            self.viewData['loginForm'] = loginForm
            return self.render('/login.html')
    
    #用户注销函数
    def logout(self, **args):
        if self.request.session.has_key(self.params.POWER):
            self.power = {'isLogin':False,'user':None}
            self.viewData['site'][self.params.POWER] = self.power
            if self.params.POWER in self.request.session:
                self.request.session.pop(self.params.POWER)
        return self.redirect('login.html')
    
    #用户注册
    def addView(self, **args):
        userForm = UserForm()
        self.viewData['userForm'] = userForm
        return self.render('/addUser.html') 
    
    @powerLevel(Params.ADMINISTRATOR)
    def listView(self, **args):
        pager = Pager(self.request)
        pager.totalSize = User.objects.all().count()
        userList = User.objects.all()
        self.viewData['userList'] = userList
        self.viewData['pager'] = pager.getPageList()
        return self.render('/admin/listUser.html')
    
    @powerLevel(Params.USER)
    def editView(self, **args):
        user = User.objects.filter(id=int(args['id']))[0]
        userForm = UserForm(self,modelData=user)
        self.viewData['userForm'] = userForm
        return self.render('/addUser.html')
    
    def loginView(self, **arges):
        loginForm = LoginForm()
        self.viewData['loginForm'] = loginForm
        return self.render('/login.html')

def action(request, **args):
    return apply(UserView(request).action, (), args)
